package com.weiyv.Updater.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

import java.io.*;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class FileTool {
    private static String TAG = "WeiyvUI";
    private static Context context;

    public static void init(Context ctx) {
        context = ctx;
    }

    public static void deleteOldUI() {
        File[] files = context.getFilesDir().listFiles(new UIFilesFilter());
        for(File file : files)
            file.delete();
    }

    static class UIFilesFilter implements FilenameFilter{
        @Override
        public boolean accept(File file, String fileName) {
            if(fileName.contains("Homepage")&&fileName.endsWith(".zip"))
                return true;
            else
                return false;
        }
    }

    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }

    public static boolean unpackZip(String path, String zipName)    {
        try {
            ZipEntry ze;
            String filename;
            InputStream ins = null;
            if (!path.endsWith("/"))
                path = path + "/";
            if(zipName.contains("/"))
                ins = new FileInputStream(zipName);
            else
                ins = new FileInputStream(path + zipName);

            ZipInputStream zis = new ZipInputStream(new BufferedInputStream(ins));
            byte[] buffer = new byte[1024];
            int count;
            while ((ze = zis.getNextEntry()) != null) {
                filename = ze.getName();
                if (ze.isDirectory()) {
                    File fmd = new File(path + filename);
                    fmd.mkdirs();
                    continue;
                }
                FileOutputStream fout = new FileOutputStream(path + filename);
                BufferedOutputStream out = new BufferedOutputStream(fout);
                while ((count = zis.read(buffer)) != -1) {
                    out.write(buffer, 0, count);
                }
                out.flush();
                out.close();
                zis.closeEntry();
            }
            zis.close();
        } catch(Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
